package com.qiaoda.web;

import com.alibaba.fastjson.JSONObject;
import com.qiaoda.entity.User;
import com.qiaoda.service.JestService;
import io.searchbox.client.JestClient;
import io.searchbox.core.SearchResult;
import io.searchbox.core.SearchResult.Hit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by Administrator on 2017/3/8 0008.
 */
@RestController
@RequestMapping("/es")
public class ElasticSearchController {

    @Autowired
    private JestService jestService;

    @RequestMapping("/test")
    public void test() throws Exception {
//        String query = "{\n" +
//                "    \"query\": {\n" +
//                "        \"filtered\" : {\n" +
//                "            \"query\" : {\n" +
//                "                \"query_string\" : {\n" +
//                "                    \"query\" : \"test\"\n" +
//                "                }\n" +
//                "            },\n" +
//                "            \"filter\" : {\n" +
//                "                \"term\" : { \"user\" : \"kimchy\" }\n" +
//                "            }\n" +
//                "        }\n" +
//                "    }\n" +
//                "}";
//        "{"query":{"match_all":{}}}
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObjectE = new JSONObject();
        jsonObject.put("match_all", new JSONObject());
        jsonObjectE.put("query", jsonObject);
        String query = jsonObjectE.toString();
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        QueryBuilder queryBuilder = QueryBuilders
//                .wildcardQuery("username", "*:*");//通配符和正则表达式查询
//        searchSourceBuilder.query(queryBuilder);
//        searchSourceBuilder.size(10);
//        searchSourceBuilder.from(0);
//        String query = searchSourceBuilder.toString();
        SearchResult search = jestService.search(query);
        jestService.closeJestClient();
        List<Hit<User, Void>> hits = search.getHits(User.class);
        System.out.println("Size:" + hits.size());
        for (Hit<User, Void> hit : hits) {
            User user = hit.source;
            System.out.println(user.toString());
        }
    }

}
